package com.jianganming.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class NioServer {

    public static void main(String[] args)throws Exception {
        ServerSocketChannel serverSocketChannel = getServerSocketChannel();

        Selector selector = Selector.open();
        //注册到selector
        serverSocketChannel.register(selector,SelectionKey.OP_ACCEPT);

        while (true){

            //服务器等待了1秒,如果没有客户端连接就轮训，直到客户端连接成功
            if(selector.select(1000)==0){
                //System.out.println("服务器等待了1秒，无连接");
                continue;
            }

            //获取选择器的key
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();

            while (iterator.hasNext()){

                SelectionKey key = iterator.next();
                //如果获得连接
                if(key.isAcceptable()){
                    //注册
                    register(serverSocketChannel,selector);
                }
                //如果是可读状态
                if(key.isReadable()){
                    //读取数据
                    readData(key);
                }

                iterator.remove();
            }
        }
    }

    private static  ServerSocketChannel getServerSocketChannel()throws Exception{
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        serverSocketChannel.socket().bind(new InetSocketAddress(9999));
        //设置为非阻塞
        serverSocketChannel.configureBlocking(false);

        return serverSocketChannel;
    }

    private static void register(ServerSocketChannel serverSocketChannel, Selector selector)throws Exception {
        SocketChannel socketChannel = serverSocketChannel.accept();

        socketChannel.configureBlocking(false);
        socketChannel.write(ByteBuffer.wrap("Hello Client,I'm NIO Server".getBytes()));
        //注册为可读的通道
        socketChannel.register(selector,SelectionKey.OP_READ);


    }

    private static void readData(SelectionKey key)throws Exception {
        SocketChannel channel = (SocketChannel)key.channel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        int count = channel.read(byteBuffer);
        if(count !=-1){
            System.out.println(new String(byteBuffer.array(),0,count));
        }
        //将缓冲区的数组指向0位置
        byteBuffer.flip();
        //清除缓冲区的数据
        byteBuffer.clear();
    }

}
